//
//  WPPPTViewController.m
//  WP_PPT
//
//  Created by GZCP1897 on 17/1/17.
//  Copyright © 2017年 GZCP1897. All rights reserved.
//

#import "WPPPTViewController.h"

@interface WPPPTViewController ()<UIWebViewDelegate>

@property(nonatomic, weak)UIWebView *webV;
@property(nonatomic, weak)UIImageView *imageV;
@end

@implementation WPPPTViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"example_ppt" ofType:@"ppt"];//WorstPresentationEverStandAlone  test_pptx
    NSString *path = [[NSBundle mainBundle] pathForResource:@"test_pptx" ofType:@"pptx"];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    UIWebView *web = [[UIWebView alloc] initWithFrame:self.view.frame];
    web.scalesPageToFit = YES;
    web.scrollView.minimumZoomScale = 0;
    web.scrollView.maximumZoomScale = 1;
    self.webV = web;
    [web loadRequest:request];
    [self.view addSubview:web];
    web.delegate = self;
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
    self.imageV = imageV;
    imageV.center = self.view.center;
    [self.view addSubview:imageV];
    
    UIButton *imageB = [UIButton buttonWithType:UIButtonTypeSystem];
    imageB.frame = CGRectMake(0, 0, 50, 25);
    [imageB setTitle:@"anniu" forState:UIControlStateNormal];
    [imageV addSubview:imageB];
    
}

#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //加载完成 可以解析html了
    [self generateThumbnailForAllSlides];
    NSString* html = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
    NSLog(@"html:\n%@", html);
    NSLog(@"---------------------华丽分割线-----------------------");
    //置空 销毁
    [self.webV removeFromSuperview];
    self.webV = nil;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"ppt加载失败---- %@", error);
}

-(void) generateThumbnailForAllSlides{
    //确定ppt有多少张幻灯片组成  21
    int slideCount = [[self.webV stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('slide').length"] intValue];
    
    //生成幻灯片图片
    for(int slideIndex = 0; slideIndex < slideCount; slideIndex++){
        @autoreleasepool {
            NSLog(@"generating: %i", slideIndex);
            // now find the dimensions of that slide
            //935
            int height = [[self.webV stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByClassName('slide')[%d].style.height", slideIndex]] intValue];
            //538
            int width= [[self.webV stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByClassName('slide')[%d].style.width", slideIndex]] intValue];
            
            // set the webview to be the same ratio of dimensions
            // as the slide, with our maximum dimension as our input.
            //
            // this way, we will only generate thumbnails that are less
            // then or equal to maxThumbnailDimension in width and height
            CGRect bounds = self.webV.bounds;//(0,0,1024,1366)
            CGFloat scale = 1;
            
            // maximum allowed size of thumbnails
            CGFloat maxThumbnailDimension = 300;
            
            //根据幻灯片真实的宽高 计算scale
            if(width > height){//  一
                
                bounds.size.width = maxThumbnailDimension;
                bounds.size.height = (float)height / (float)width * maxThumbnailDimension;
                scale = maxThumbnailDimension / width; //   300 / 720
                
            }else{//  1
                
//                scale = bounds.size.width / bounds.size.height;
                bounds.size.width = (float)width / (float)height * maxThumbnailDimension;
                bounds.size.height = maxThumbnailDimension;
                scale = maxThumbnailDimension / height;
                
            }
            self.webV.bounds = bounds;
            
            // next, find out how far down in the webview this slide is
            // and scroll to it
            //根据偏移量 把对应幻灯片滚动到界面上
            int offset = [[self.webV stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByClassName('slide')[%d].offsetTop", slideIndex]] intValue];
            CGPoint so = self.webV.scrollView.contentOffset;
            so.y = offset * scale;
            self.webV.scrollView.contentOffset = so;
            
            // now that the webview's bounds are exactly the same size
            // then save the webview as a PNG image of the slide
            UIGraphicsBeginImageContext(bounds.size);
            [self.webV.layer renderInContext:UIGraphicsGetCurrentContext()];
            UIImage *slideThumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            
            // save the slide to our Documents directory.
            // you can verify the output in Xcode's Organizer,
            // or by modifying the project to show UIImageViews
            // or however you like
            NSString* filename = [NSString stringWithFormat:@"slide%i.png", slideIndex];
            NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//            NSString *outputImagePath = [[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:filename];
            NSString *macPath = @"Users/gzcp1897/Desktop/pptFile";
            NSString *outputImagePath = [macPath stringByAppendingPathComponent:filename];
            
            
            [UIImagePNGRepresentation(slideThumbnailImage) writeToFile:outputImagePath atomically:YES];
            
            if (slideIndex == 0) {
                
                self.imageV.contentMode = UIViewContentModeCenter;
                self.imageV.image = slideThumbnailImage;
                
            }
            


        }
    }
    
//    scrollView.contentSize = CGSizeMake(MAX(768,self.view.bounds.size.width), (floorf(slideCount / 2)+1) * 300);
//    status.text = [NSString stringWithFormat:@"Generated %i thumbnails", slideCount];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
